package it.softphone.cmc.server.rest;

import it.softphone.cmc.server.service.SystemManagerService;
import it.softphone.cmc.server.service.TenantService;
import it.softphone.cmc.shared.entity.Tenant;
import it.softphone.commons.service.LogAware;
import it.softphone.commons.spring.ApplicationConfig;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.CacheControl;
import javax.ws.rs.core.Response;



@Path("/resources")
public class CMCRestResources implements LogAware {

	
	@GET 
    @Produces("image/*")
    @Path("{resource}")
    public Response getResource(@PathParam("resource") String resource ) {
		
		SystemManagerService service = ApplicationConfig.getBean(SystemManagerService.class);
		TenantService tenantService = ApplicationConfig.getBean(TenantService.class);
		
		try {
			String tenant = tenantService.getCurrentTenant();
			
			Tenant e = service.findTenantById( "name", tenant);
			
			if( e!=null ) {
				
				java.io.ByteArrayInputStream  b = new java.io.ByteArrayInputStream(e.getLogoB());
				
				CacheControl cc = new CacheControl();
				cc.setNoCache(true);
				
				return Response.ok( b ).cacheControl(cc).build();
			}
			else {
				logger.warn( String.format("Tenant with name [%s] not found!", tenant ) );
			}
			
		} catch (Exception e) {
			logger.error("error getting resource from tenant [%s]", e);
		}
		
		return Response.noContent().build();

	}
	
}
